<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('压力监测')"/>
    <script type="text/javascript" th:src="@{/js/echarts.min.js}"></script>
</head>
<body>
<body style="height: 100%; margin: 0">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <label for="recordTime">记录时间：</label>
            <input type="text" id="recordTime" class="time-input" placeholder="请选择记录时间" th:value="${#dates.format(new java.util.Date().getTime(),'yyyy-MM-dd')}" name="recordTime"/>
            <a class="btn btn-primary btn-rounded btn-sm" onclick="searchHistory()"><i class="fa fa-search"></i>&nbsp;搜索</a>
        </div>
        <div id="container" class="col-sm-12 select-table table-striped">
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<script th:inline="javascript">
    let prefix = ctx + "system/record/";
    let dom;
    let myChart;
    let option = null;
    let recordDTOList = [[${recordDTOList}]];
    let plantIds = [];
    let length = recordDTOList.length;
    let series = [];
    // 设置警戒值
    let warnNum = 500;
    let markLine = {   //添加警戒线
        symbol:"none",               //去掉警戒线最后面的箭头
        name:"警戒线",
        silent:true,
        label:{
            position:"end",         //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
            formatter: "警戒线(" +warnNum+ ")",
            color:"red",
            fontSize:14
        },
        data : [{
            silent:true,             //鼠标悬停事件  true没有，false有
            lineStyle:{               //警戒线的样式  ，虚实  颜色
                type:"solid",
                color:"red"
            },
            name: '警戒线',
            yAxis: warnNum
        }]
    };


    // 设置同步
    $.ajax.async=false;
    // 每分钟获取设备数据
    function getData() {
        $.get(prefix+"getData",(res)=>{
            res.forEach((item,index)=>{
                // 因为只有一条记录
                let record = item.recordList[0];
                let now = new Date(record.recordTime);
                let valueName = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + ' ' + (now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()) + ':' + (now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes());
                data[index].push(new Point(parserDate(record.recordTime).toString(),valueName,record.pressure));
            });
        });
    }

    // 根据length，初始化data
    let data = [];

    initChart();

    function initChart() {
        dom = document.getElementById("container");
        myChart = echarts.init(dom);
        for(let i=0;i<length;i++){
            data.push([]);
        }

        // 遍历每个plant的recordList，初始化多条折线
        recordDTOList.forEach((item,i)=>{
            plantIds.push(item.plantId+"");
            // 取出该设备的初始化温度列表
            item.recordList.forEach((it,j)=>{
                //初始化有多少个点
                // 每个点是一个对象，包含了
                let now = new Date(it.recordTime);
                let valueName = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + ' ' + (now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()) + ':' + (now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes());
                data[i].push(new Point(parserDate(it.recordTime).toString(),valueName,it.pressure));
            });
        });

        plantIds.forEach((item,index)=>{
            series.push({
                name: item+"",
                type: 'line',
                showSymbol: false,
                hoverAnimation: false,
                data: data[index],
                markLine: markLine
            })
        });

        option = {
            // tooltip 是提示框组件
            tooltip: {
                // 坐标轴触发
                trigger: 'axis',
                formatter: (params)=> {
                    // 获取到新增的randomData返回的对象
                    params = params[0];
                    var date = new Date(params.name);
                    return  "[" + date.getFullYear() + '/' + (date.getMonth() + 1) + "/" + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ']' + '\t温度: ' + params.value[1]+"℃";
                },
                axisPointer: {
                    type: 'cross'
                },
            },
            toolbox: {
                show: true,
                feature: {
                    saveAsImage: {
                        show: true,
                        excludeComponents: ['toolbox'],
                        pixelRatio: 2
                    }
                }
            },

            dataZoom: [
                {
                    show: true,
                    realtime: true,
                    start: 30,
                    end: 70,
                    xAxisIndex: [0, 1]
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 30,
                    end: 70,
                    xAxisIndex: [0, 1]
                }
            ],

            xAxis: {
                type: 'time',
                splitLine: {
                    show: false
                },
                axisLabel:{interval:1}
            },
            yAxis: {
                name: '压力（kpa）',
                type: 'value',
                boundaryGap: [0, '100%'],
                splitLine: {
                    show: true
                }
            },
            legend: {
                // data: ['模拟数据1', '模拟数据2', '模拟数据3']
                data: plantIds
            },
            series: series
        };
        if (option && typeof option === "object") {
            myChart.setOption(option, true);
        }
    }

    // 设置定时器，设置时间间隔为1分钟
    let timer = setInterval(()=>{
        getData();

        // 更新series
        myChart.setOption({
            series: series
        });
    }, 60000);

    function Point(now,valueName,val) {
        this.name = now.toString();
        this.value = [valueName, val];
    }

    // 将2021-4-7 这样的格式转换为Thu April 7 这样的格式
    function parserDate(date) {
        let t = Date.parse(date);
        if (!isNaN(t)) {
            return new Date(Date.parse(date.replace(/-/g, '/')))
        }
    }

    // 查询历史设备温度折线图
    function searchHistory() {
        let recordTime = $("#recordTime").val();
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth()+1;
        month = month<10 ? "0"+month : month;
        let date = now.getDate();
        date = date<10 ? "0"+date : date;
        let str = year + '-' + month + "-" + date;
        if(recordTime!=str){
            // 查询历史记录，不需要每分钟更新数据
            window.clearInterval(timer);
            $.get(prefix+"getHistory",{"recordTime":recordTime},(res)=>{
                if(res!=null && res.length!=0){
                    option = [];
                    data = [];
                    plantIds = [];
                    series = [];
                    recordDTOList = res;
                    length = res.length;
                    initChart();
                }else{
                    let html = '<div><sapn style="font-size: 18px;font-weight: bold;">设备监测：</sapn><span  style="position: absolute;top: 40%;margin-left: 10%;color:#868686; font-size: 20px;">暂无数据</span></div>'
                    document.getElementById('container').innerHTML = html
                    document.getElementById('container').removeAttribute('_echarts_instance_')
                }
            });
        }else{
            // 刷新页面
            window.history.go(0);
        }
    }
</script>
</body>
</html>